# -*- coding: utf-8 -*-

#-----------------------------------------------------------------------------
# 库文件
#-----------------------------------------------------------------------------
import serial

# 导入命令行参数
from parse_definition import args
from log import *

#-----------------------------------------------------------------------------
# 函数定义
#-----------------------------------------------------------------------------

# 串口打开，需要输入串口名 和 波特率


def serial_port_open(port, baudrate):
    sp = serial.Serial()
    sp.baudrate = baudrate
    sp.port = port
    sp.timeout = 1

    if (sp.is_open):
        LOGI("serial port" + port + "was opened...")
    else:
        LOGI("serial port" + port + "is opening...")
        sp.open()

    return sp

# 串口关闭，需要输入串口名


def serial_port_close(port):
    sp = serial.Serial()
    sp.port = port
    LOGI("serial port" + port + "is closing...")
    sp.close()


# 尝试打开串口并获取数据，不断循环打印数据
def task_log_printf(sp, log_file_path):
    # 文件写入
    with open(log_file_path, "ab") as f:
            if (sp.in_waiting):  # 是否收到数据
                b = sp.readline()  # 读取一行数据
                f.write(b)  # 写入文件
                # f.close()
                # LOGI(b)  # 打印至屏幕


if __name__ == '__main__':
    log_file_path = args.log_path + args.log_name
    sp = serial_port_open(args.port, 115200)
    task_log_printf(sp, log_file_path)
    serial_port_close(args.port)
